package com.chinawlx.wlxteacher.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bigkoo.alertview.AlertView;
import com.bigkoo.alertview.OnItemClickListener;
import com.chinawlx.wheelview.OptionsPickerView;
import com.chinawlx.wlxteacher.R;
import com.chinawlx.wlxteacher.network.WLXHttpRxHelper;
import com.chinawlx.wlxteacher.network.bean.WLXGetCodeBean;
import com.chinawlx.wlxteacher.utils.WLXConstant;
import com.chinawlx.wlxteacher.utils.WLXLogUtil;
import com.chinawlx.wlxteacher.utils.WLXWheelViewUtils;
import com.chinawlx.wlxteacher.widget.WLXChooseLessonView;
import com.chinawlx.wlxteacher.widget.WLXCustomToast;

import java.util.ArrayList;
import java.util.Calendar;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import rx.Subscriber;

/**
 * 作者:黄帅
 * 时间:16/9/10
 * 描述:添加课程
 */
public class WLXClazzAddActivity extends WLXBaseActivity {

    @BindView(R.id.iv_back)
    ImageView mIvBack;
    @BindView(R.id.tv_save)
    TextView mTvSave;
    @BindView(R.id.tv_clazz_name)
    TextView mTvClazzName;
    @BindView(R.id.iv_right_jiantou)
    ImageView mIvRightJiantou;
    @BindView(R.id.tv_add_lesson_student)
    TextView mTvAddLessonStudent;
    @BindView(R.id.rl_add_lesson_student)
    RelativeLayout mRlAddLessonStudent;
    @BindView(R.id.iv_adjust)
    ImageView mIvAdjust;
    @BindView(R.id.tv_center_adjust_line)
    TextView mTvCenterAdjustLine;
    @BindView(R.id.choose_adjust_lesson)
    WLXChooseLessonView mChooseDateLeft;
    @BindView(R.id.choose_adjust_lesson_to)
    WLXChooseLessonView mChooseDateRight;
    @BindView(R.id.tv_show_add_lesson_time)
    TextView mTvShowAddLessonTime;
    @BindView(R.id.tv_add_lesson_time)
    TextView mTvAddLessonTime;
    @BindView(R.id.rl_add_lesson_time)
    RelativeLayout mRlAddLessonTime;


    public boolean isAddGrade = true;//是否是整个班级都加课
    private String mStudentId;
    private String week;
    private String start_time;
    private String end_time;
    private String start_date;
    private String end_date;

    private ArrayList<String> times = new ArrayList<>();//给滚轮显示用
    private ArrayList<String> times2 = new ArrayList<>();//计算星期几用
    private int firstPosition = -1;
    private int seconPosition = -1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_lesson);
        ButterKnife.bind(this);
        init();
    }

    private void init() {
        initData();
        initView();
    }

    private void initView() {
        restoreState();
    }

    private void initData() {
        initTimes();
    }

    @OnClick({R.id.iv_back, R.id.tv_save, R.id.rl_add_lesson_student, R.id.choose_adjust_lesson,
            R.id.choose_adjust_lesson_to, R.id.rl_add_lesson_time})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.tv_save:
                if (checkIfComplete()) {
                    requestNet4AddLesson();
                }
                break;
            case R.id.rl_add_lesson_student:
                startActivityForResult(new Intent(WLXClazzAddActivity.this,
                        WLXChooseStudentActivity.class), 0);
                break;
            case R.id.choose_adjust_lesson:
                if (TextUtils.isEmpty(mStudentId)) {
                    WLXCustomToast.show("请先选择加课人员");
                    return;
                }
                WLXWheelViewUtils.showOneWheel(this, times, "选择加课开始日期", 0, new OptionsPickerView
                        .OnOptionsSelectListener() {

                    @Override
                    public void onOptionsSelect(int options1, int option2, int options3) {
                        String time = times.get(options1);
                        String[] split = time.split("年");
                        setChooseLesson(split[1], "开始", "", WLXChooseLessonView.ChooseMode
                                .YELLOWROUND);

                        start_date = time.replace("年", "-").replace("月", "-").replace("日", "");
                        firstPosition = options1;
                    }
                });
                break;
            case R.id.choose_adjust_lesson_to:
                if (firstPosition == -1) {
                    WLXCustomToast.show("请先选择开始时间");
                    return;
                }
                WLXWheelViewUtils.showOneWheel(this, times, "选择加课结束日期", 0, new OptionsPickerView
                        .OnOptionsSelectListener() {

                    @Override
                    public void onOptionsSelect(int options1, int option2, int options3) {
                        if (options1 < firstPosition) {
                            WLXCustomToast.show("结束时间不得小于开始时间");
                            setChooseLessonTo("选择", "结束时间", "", WLXChooseLessonView.ChooseMode
                                    .GRAY);
                            return;
                        }
                        String time = times.get(options1);
                        end_date = time.replace("年", "-").replace("月", "-").replace("日", "");
                        String[] split = time.split("年");
                        setChooseLessonTo(split[1], "结束", "",
                                WLXChooseLessonView
                                        .ChooseMode.YELLOWROUND);
                        seconPosition = options1;
                    }
                });
                break;
            case R.id.rl_add_lesson_time:
                if (TextUtils.isEmpty(start_date) || TextUtils.isEmpty(end_date)) {
                    WLXCustomToast.show("请先选择开始和结束时间");
                    return;
                }
                ArrayList<String> showWeeks = getShowWeeks(firstPosition, seconPosition);
                WLXWheelViewUtils.showThreeWheel(this, showWeeks
                        , "选择加课时间", 0, 0, 0, new OptionsPickerView
                                .OnOptionsSelectListener() {

                            @Override
                            public void onOptionsSelect(int options1, int option2, int options3) {
                                WLXLogUtil.d("选中的位置: " + options1 + "-" + option2 + "-" + options3);
                                start_time = WLXWheelViewUtils.getStartTime(options1, option2,
                                        options3);
                                end_time = WLXWheelViewUtils.getEndTime(options1, option2,
                                        options3);
                                mTvAddLessonTime.setText(WLXWheelViewUtils.weeks.get(options1) +
                                        "       " +
                                        "       " +
                                        start_time + "-" + end_time);
                                options1++;
                                week = options1 + "";
                            }
                        });
                break;
        }
    }

    //检查请求数据
    private boolean checkIfComplete() {

        if (TextUtils.isEmpty(mStudentId) || TextUtils.isEmpty(start_date) || TextUtils
                .isEmpty(end_date) || TextUtils.isEmpty(start_time) || TextUtils.isEmpty
                (end_time) || TextUtils
                .isEmpty(week)) {
            return false;
        }

        return true;
    }

    private void initTimes() {
        Calendar calendar = Calendar.getInstance();
        for (int i = 0; i < 30; i++) {
            int year = calendar.get(Calendar.YEAR);
            int monthNum = calendar.get(Calendar.MONTH);
            int dayNum = calendar.get(Calendar.DAY_OF_MONTH);
            times2.add(year + "," + monthNum + "," + dayNum);

            monthNum++;
            String month = monthNum + "";
            String day = dayNum + "";
            if (monthNum < 10) {
                month = "0" + monthNum;
            }
            if (dayNum < 10) {
                day = "0" + dayNum;
            }

            String time = year + "年" + month + "月" + day + "日";
            times.add(time);

            //当前天数加1
            calendar.add(Calendar.DAY_OF_MONTH, 1);
        }
    }

    //当返回null的时候,工具类会直接显示所有
    private ArrayList<String> getShowWeeks(int start, int end) {
        if (end - start >= 7 || end - start < 0) {
            return null;
        }
        ArrayList<String> showWeeks = new ArrayList<>();
        int startIndex = getWeekIndex(start);
        int endIndex = getWeekIndex(end);
        if (startIndex <= endIndex) {
            //情况一：startIndex <= endIndex
            for (int i = startIndex; i <= endIndex; i++) {
                showWeeks.add(weeks[i]);
            }
        } else {
            //情况二：startIndex > endIndex
            while (startIndex <= 6 || endIndex >= 0) {
                if (startIndex <= 6) {
                    showWeeks.add(weeks[startIndex]);
                    startIndex++;
                }
                if (endIndex >= 0) {
                    showWeeks.add(weeks[endIndex]);
                    endIndex--;
                }
            }
        }

        return showWeeks;
    }

    String[] weeks = {"星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"};

    private int getWeekIndex(int index) {
        String[] split = times2.get(index).split(",");

        Calendar calendar = Calendar.getInstance();
        calendar.set(Integer.valueOf(split[0]), Integer.valueOf(split[1]), Integer.valueOf
                (split[2]));
        int week_index = calendar.get(Calendar.DAY_OF_WEEK) - 1;
        if (week_index < 0) {
            week_index = 0;
        }
        return week_index;
    }


    private void requestNet4AddLesson() {
        if (isAddGrade) {
            WLXHttpRxHelper.getInstance().scheduleAddGrade(WLXConstant.GRADE_ID, week,
                    start_time, end_time, start_date, end_date, new Subscriber<WLXGetCodeBean>() {


                        @Override
                        public void onCompleted() {

                        }

                        @Override
                        public void onError(Throwable e) {

                        }

                        @Override
                        public void onNext(WLXGetCodeBean wlxGetCodeBean) {
                            if (wlxGetCodeBean.getCode() == 0) {
                                new AlertView("提示", "加课成功", null, new String[]{"确定"}, null,
                                        WLXClazzAddActivity.this,
                                        AlertView.Style.Alert, new OnItemClickListener() {
                                    @Override
                                    public void onItemClick(Object o, int position) {
                                        restoreState();
                                    }
                                }).show();
                            } else {
                                WLXCustomToast.show(wlxGetCodeBean.getMsg());
                            }
                        }
                    });
        } else {
            WLXHttpRxHelper.getInstance().scheduleAddStudent(WLXConstant.GRADE_ID, mStudentId,
                    week, start_time, end_time, start_date, end_date, new
                            Subscriber<WLXGetCodeBean>() {


                                @Override
                                public void onCompleted() {

                                }

                                @Override
                                public void onError(Throwable e) {

                                }

                                @Override
                                public void onNext(WLXGetCodeBean wlxGetCodeBean) {
                                    if (wlxGetCodeBean.getCode() == 0) {
                                        new AlertView("提示", "加课成功", null, new String[]{"确定"}, null,
                                                WLXClazzAddActivity.this,
                                                AlertView.Style.Alert, new OnItemClickListener() {
                                            @Override
                                            public void onItemClick(Object o, int position) {
                                                restoreState();
                                            }
                                        }).show();
                                    } else {
                                        WLXCustomToast.show(wlxGetCodeBean.getMsg());
                                    }
                                }
                            });
        }
    }


    //恢复到初始状态
    private void restoreState() {
        //1.恢复调课原因
        //TODO


        //2.恢复调课时间
        setChooseLesson("选择", "开始时间", "", WLXChooseLessonView.ChooseMode.GRAY);
        setChooseLessonTo("选择", "结束时间", "", WLXChooseLessonView.ChooseMode.GRAY);

        //3.停课人员

    }

    //上面+下面+模式:左边
    public void setChooseLesson(String top, String bottom, String line, WLXChooseLessonView
            .ChooseMode mode) {
        mChooseDateLeft.setTop(top);
        mChooseDateLeft.setBottom(bottom);
        mChooseDateLeft.changeMode(mode);
        mTvCenterAdjustLine.setText(line);
    }

    //上面+下面+模式:右边
    public void setChooseLessonTo(String top, String bottom, String line, WLXChooseLessonView
            .ChooseMode mode) {
        mChooseDateRight.setTop(top);
        mChooseDateRight.setBottom(bottom);
        mChooseDateRight.changeMode(mode);
        mTvCenterAdjustLine.setText(line);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_CANCELED) {
            return;
        }
        if (resultCode == RESULT_OK) {
            int student_id = data.getIntExtra(WLXChooseStudentActivity.STUDENT_ID, -1);
            String names = data.getStringExtra(WLXChooseStudentActivity.STUDENT_NAME);
            mTvAddLessonStudent.setVisibility(View.VISIBLE);
            mTvAddLessonStudent.setText(names + "");
            if (student_id == -1) {
                //选择了所有学生
                isAddGrade = true;
                mStudentId = "0";
            } else {
                isAddGrade = false;
                mStudentId = student_id + "";
            }

        }
    }
}
